package com.hopes.bizz.close.shardingsphere.strategy;

import cn.hutool.json.JSONUtil;
import com.hopes.bizz.common.core.util.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.sharding.api.sharding.standard.PreciseShardingValue;
import org.apache.shardingsphere.sharding.api.sharding.standard.RangeShardingValue;
import org.apache.shardingsphere.sharding.api.sharding.standard.StandardShardingAlgorithm;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;

/**
 * @author yumr
 * @ProjectName bizz
 * @Description 历史数据库分表
 * @time 2024/1/31 11:04
 */
@Slf4j
public class HisPositionStandardAlgorithm implements StandardShardingAlgorithm<Date> {


    @Override
    public String doSharding(Collection<String> availableTargetNames, PreciseShardingValue<Date> shardingValue) {
        final String shardingName = shardingValue.getLogicTableName() + "_" + DateUtils.getYear(shardingValue.getValue());
        log.debug("==> 单日期SQL分表 {}", shardingName);
        return shardingName;
    }

    @Override
    public Collection<String> doSharding(Collection<String> availableTargetNames, RangeShardingValue<Date> shardingValue) {
        final List<String> result = new ArrayList<>();
        result.add(shardingValue.getLogicTableName() + "_" + DateUtils.limitYear(shardingValue.getValueRange().lowerEndpoint()));
        result.add(shardingValue.getLogicTableName() + "_" + DateUtils.limitYear(shardingValue.getValueRange().upperEndpoint()));
        log.debug("==> 单日期SQL分表 {}", JSONUtil.toJsonStr(result));
        return result;
    }

    @Override
    public void init() {

    }

    @Override
    public String getType() {
        return "HisPositionStandardAlgorithm";
    }
}
